package com.ruoyi.web.controller.shop.shop.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.GetPlayInfoResponse;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.OSSUtil;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.web.controller.city.service.ICmsCityService;
import com.ruoyi.web.controller.mall.shopExtract.service.IShopExtractService;
import com.ruoyi.web.controller.shop.imgs.domain.ShopImages;
import com.ruoyi.web.controller.shop.imgs.service.IShopImagesService;
import com.ruoyi.web.controller.shop.shop.domain.ShopShop;
import com.ruoyi.web.controller.shop.shop.service.IShopShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;

import static com.ruoyi.web.utils.initVodClient.getPlayInfo;
import static com.ruoyi.web.utils.initVodClient.initVodClient;


/**
 * 店铺信息Controller
 * 
 * @author ruoyi
 * @date 2020-10-15
 */
@RestController
@RequestMapping("/shop/shop")
public class ShopShopController extends BaseController
{
    @Autowired
    private IShopShopService shopShopService;
    
    @Autowired
    private IShopImagesService shopImagesService;

    @Autowired
    private ICmsCityService cmsCityService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private IShopExtractService shopExtractService;

    /**
     * 查询店铺信息列表
     */
    @GetMapping("/list")
    public AjaxResult list(ShopShop shopShop)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        //查询店铺信息
        ShopShop select = this.shopShopService.selectShopShopById(user.getShopId());
        if(select==null){
            return AjaxResult.error("门店不存在");
        }
        //设置查询总店下的分店列表
        shopShop.setParentId(select.getId());
        startPage();
        List<ShopShop> list = shopShopService.selectShopShopList(shopShop);
        return AjaxResult.success(getDataTable(list));
    }

    /**
     * 获取店铺信息详细信息
     */
//    @PreAuthorize("@ss.hasPermi('shop:shop:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        HashMap<String, Object> map = new HashMap<>();
        // 店铺信息
        ShopShop shopShop = shopShopService.selectShopShopById(id);
        BigDecimal amount = shopExtractService.countByShopId(id);
        shopShop.setAmount(amount);
//        shopShop.setHasAccount(this.accountService.findHasAccount(id,DateUtils.getNowDate()));
        map.put("shopShop",shopShop);

//        //分类列表
//        ShopClass selectClass = new ShopClass();
//        selectClass.setStatus(0);
//        selectClass.setDelFlag(0);
//        List<ShopClass> shopClassList = this.shopClassService.selectShopClassList(selectClass);
//        map.put("classList",shopClassList);
        return AjaxResult.success(map);
    }


    /**
     * 获取店铺信息详细信息
     */
//    @PreAuthorize("@ss.hasPermi('shop:shop:query')")
    @GetMapping(value = "/{id}/imgs")
    public AjaxResult getShopImgs(@PathVariable("id") String id) {
        HashMap<String, Object> map = new HashMap<>();
        // 店铺轮播图片
        ShopImages shopImages = new ShopImages();
        shopImages.setLinkId(id);
        shopImages.setAddress(0);
        List<ShopImages> banner = this.shopImagesService.selectShopImagesList(shopImages);
        //店铺内部环境
        shopImages.setAddress(1);
        List<ShopImages> inside = this.shopImagesService.selectShopImagesList(shopImages);
        //店铺外部环境
        shopImages.setAddress(2);
        List<ShopImages> external = this.shopImagesService.selectShopImagesList(shopImages);

        shopImages.setAddress(5);
        List<ShopImages> videos = this.shopImagesService.selectShopImagesList(shopImages);
        if(videos.size()>0){
            try {
                //            map.put("video",banner);
                String video =videos.get(0).getImgurl();
                DefaultAcsClient client = initVodClient();
                GetPlayInfoResponse response = new GetPlayInfoResponse();

                response = getPlayInfo(client,video);
                List<GetPlayInfoResponse.PlayInfo> playInfoList = response.getPlayInfoList();
                //播放地址
                for (GetPlayInfoResponse.PlayInfo playInfo : playInfoList) {
                    System.out.print("PlayInfo.PlayURL = " + playInfo.getPlayURL() + "\n");
//                video.setUrl(playInfo.getPlayURL());
//                cs.setImgHead(playInfo.getPlayURL());
                    map.put("video",playInfo.getPlayURL());
                }
            }catch (Exception e){
                map.put("video",videos.get(0).getImgurl());
            }

        }else {
            map.put("video","");
        }
        map.put("banner",banner);
        map.put("inside",inside);
        map.put("external",external);
        return AjaxResult.success(map);
    }


    /**
     * 新增店铺信息
     */
//    @PreAuthorize("@ss.hasPermi('shop:shop:add')")
    @Log(title = "店铺信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ShopShop shopShop)
    {
        shopShop.setDelFlag(0);
        shopShop.setCheck(3);
        shopShop.setCreateAt(DateUtils.getNowDate());
        shopShop.setGradeEnvironment(new BigDecimal(0));
        shopShop.setSpecialShop(0);
        //城市不允许选择全部
        if(shopShop.getCityId()==null||shopShop.getCityId()==0){
            return AjaxResult.error("重新选择城市");
        }
        return toAjax(shopShopService.insertShopShop(shopShop));
    }

    /**
     * 修改店铺信息
     */
//    @PreAuthorize("@ss.hasPermi('shop:shop:edit')")
    @Log(title = "店铺信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ShopShop shopShop)
    {


//        return toAjax(shopShopService.updateShopShop(shopShop));
        return shopShopService.changeShopShop(shopShop);
    }

    /**
     * 删除店铺信息
     */
//    @PreAuthorize("@ss.hasPermi('shop:shop:remove')")
    @Log(title = "店铺信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(shopShopService.deleteShopShopByIds(ids));
    }



    /**
     * 上传店铺相关图片
     */
//    @PreAuthorize("@ss.hasPermi('shop:goods:edit')")
    @Log(title = "上传店铺相关图片", businessType = BusinessType.UPDATE)
    @PostMapping("/upload")
    @Transactional
    public AjaxResult uploadGoodsImg(MultipartFile file, @RequestParam(value = "type",required = false) Integer type,
                                     @RequestParam(value = "resId",required = false) String resId){

        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        //查询店铺信息
        ShopShop shopShop = this.shopShopService.selectShopShopById(user.getShopId());
        if(shopShop==null){
            return AjaxResult.error("门店不存在");
        }
        try {
            String imagePath =new OSSUtil().uploadImageToOSS(file.getOriginalFilename(),file.getInputStream());
            if (StringUtils.isBlank(imagePath)) {
                return  AjaxResult.error("上传失败");
            }
            //增加图片信息
            ShopImages shopImages = new ShopImages();
            shopImages.setLinkId(resId);
            shopImages.setAddress(type);
            shopImages.setCreateAt(DateUtils.getNowDate());
            shopImages.setCreateId(user.getUserId());
            shopImages.setStatus(0);
            shopImages.setImgurl(imagePath);
            shopImages.setShopId(shopShop.getId());
            this.shopImagesService.insertShopImages(shopImages);
            return AjaxResult.success(shopImages);
        } catch (Exception e) {
            return AjaxResult.error();
        }
    }

    /**
     * 删除图片资源
     * @param imgId
     * @return
     */
    @DeleteMapping("/file")
    @Transactional
    public AjaxResult clearGoodsFile(@RequestParam String imgId) {
        //删除图片
        this.shopImagesService.deleteShopImagesById(imgId);
        return AjaxResult.success();
    }

}
